package jmars.mobile.worker;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jmars.mobile.common.Investigator;
import jmars.mobile.datainvestigation.Summary;
import jmars.mobile.domain.NumericalFeature;

public class QuantileStat implements Investigator {

	@Override
	public Integer compute(File[] files, FileWriter writer) throws IOException {
		Integer total = 0;
		FileInputStream fis;
		BufferedReader reader;
		String row;
		String[] cols;
		Map<String,NumericalFeature> stat=new HashMap<String,NumericalFeature>();
		Map<String,List<Double>> tempMap=new HashMap<String,List<Double>>();
		NumericalFeature rowStat;
		DecimalFormat df = new DecimalFormat();
		df.applyPattern("0,000");
		Double temp;
		for(File inputFile:files){
			fis = new FileInputStream(inputFile);
			reader = new BufferedReader(new InputStreamReader(fis));
			while((row=reader.readLine())!=null){
				cols=row.split(Summary.columnSeperator);
				if(Summary.filterRow(cols,false,true)) continue;
				total++;
				for(Integer idx:Summary.targetColumnIdx){
					if(idx<cols.length){
						if(stat.containsKey(Summary.columns[idx])) rowStat=stat.get(Summary.columns[idx]);
						else{
							rowStat = new NumericalFeature();
							tempMap.put(Summary.columns[idx], new ArrayList<Double>());
						}
						temp = Double.parseDouble(cols[idx]);
						tempMap.get(Summary.columns[idx]).add(Double.parseDouble(cols[idx]));
						rowStat.update(temp);
						stat.put(Summary.columns[idx], rowStat);
					}
				}
			}
			reader.close();
			fis.close();
			System.out.println(inputFile.getName()+" finished at "+total);
		}
		for(Integer idx:Summary.targetColumnIdx){
			Collections.sort(tempMap.get(Summary.columns[idx]));
			stat.get(Summary.columns[idx]).setlQuart(tempMap.get(Summary.columns[idx]).get(total/4));
			stat.get(Summary.columns[idx]).setMed(tempMap.get(Summary.columns[idx]).get((total/2)));
			stat.get(Summary.columns[idx]).setuQuart(tempMap.get(Summary.columns[idx]).get(total*3/4));
		}
		writer.write("%total:"+df.format(total)+"\r\n");
		if(stat.size()<=1000){
			writer.write("%*****************details******************\r\n");
			for(String s:stat.keySet()){
				writer.write(s.replaceAll("\\$_\\$\\$_\\$", ",").replaceAll("\\$_\\$","")+","+stat.get(s)+"\r\n");
			}
		}
		return total;
	}

}
